﻿using CefSharp.WinForms;
using System.Collections.Generic;

namespace AwesomeChromeFormUI.Cache
{
    internal sealed class GlobalBrowserCache
    {
        private Dictionary<string, ChromiumWebBrowser> _browserCache;

        /// <summary>
        /// 单例模式
        /// </summary>
        private static readonly GlobalBrowserCache _cache = null;

        public static GlobalBrowserCache Cache
        {
            get { return _cache; }
        }

        /// <summary>
        /// 私有化构造函数
        /// </summary>
        private GlobalBrowserCache()
        {
            this._browserCache = new Dictionary<string, ChromiumWebBrowser>();
        }

        /// <summary>
        /// 静态构造函数
        /// </summary>
        static GlobalBrowserCache()
        {
            _cache = new GlobalBrowserCache();
        }

        /// <summary>
        /// 新增缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Add(string key, ChromiumWebBrowser value)
        {
            if (this._browserCache.ContainsKey(key))
            {
                this._browserCache[key] = value;
                return;
            }
            this._browserCache.Add(key, value);
        }


        /// <summary>
        /// 更新缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Update(string key, ChromiumWebBrowser value)
        {
            if (this._browserCache.ContainsKey(key))
            {
                this._browserCache[key] = value;
                return;
            }

            this.Add(key, value);
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Remove(string key)
        {
            return this._browserCache.Remove(key);
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public ChromiumWebBrowser GetValueByKey(string key)
        {
            if (this._browserCache.ContainsKey(key))
            {
                return this._browserCache[key];
            }
            return null;
        }
    }
}
